package com.pap.gateway.exception;

import com.pap.gateway.config.security.core.exception.enums.JWTExceptionEnum;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.*;

import java.util.HashMap;
import java.util.Map;

/**
 * Spring Cloud Gateway的全局异常处理
 *  Spring Cloud Gateway中的全局异常处理不能直接用@ControllerAdvice来处理，通过跟踪异常信息的抛出，找到对应的源码，自定义一些处理逻辑来符合业务的需求。
 *  网关都是给接口做代理转发的，后端对应的都是REST API，返回数据格式都是JSON。如果不做处理，当发生异常时，Gateway默认给出的错误信息是页面，不方便前端进行异常处理。
 *  需要对异常信息进行处理，返回JSON格式的数据给客户端。
 */
public class JsonErrorWebExceptionHandler extends DefaultErrorWebExceptionHandler {

    public JsonErrorWebExceptionHandler(ErrorAttributes errorAttributes,
                                        ResourceProperties resourceProperties,
                                        ErrorProperties errorProperties,
                                        ApplicationContext applicationContext) {
        super(errorAttributes, resourceProperties, errorProperties, applicationContext);
    }

    @Override
    protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
        int code = 500;
        Throwable error = super.getError(request);
        if (error instanceof org.springframework.cloud.gateway.support.NotFoundException) {
            code = 404;
        }
        if (error instanceof com.pap.gateway.config.security.core.exception.PapEmptyJwtException) {
            return response(JWTExceptionEnum.PapEmptyJwtException.getCode(), JWTExceptionEnum.PapEmptyJwtException.getMsg());
        } else
        if (error instanceof com.pap.gateway.config.security.core.exception.PapExpiredJwtException) {
            return response(JWTExceptionEnum.PapExpiredJwtException.getCode(), JWTExceptionEnum.PapExpiredJwtException.getMsg());
        } else
        if (error instanceof com.pap.gateway.config.security.core.exception.PapIllegalArgumentException) {
            return response(JWTExceptionEnum.PapIllegalArgumentException.getCode(), JWTExceptionEnum.PapIllegalArgumentException.getMsg());
        } else
        if (error instanceof com.pap.gateway.config.security.core.exception.PapMalformedJwtException) {
            return response(JWTExceptionEnum.PapMalformedJwtException.getCode(), JWTExceptionEnum.PapMalformedJwtException.getMsg());
        } else
        if (error instanceof com.pap.gateway.config.security.core.exception.PapSignatureException) {
            return response(JWTExceptionEnum.PapSignatureException.getCode(), JWTExceptionEnum.PapSignatureException.getMsg());
        } else
        if (error instanceof com.pap.gateway.config.security.core.exception.PapUnsupportedJwtException) {
            return response(JWTExceptionEnum.PapUnsupportedJwtException.getCode(), JWTExceptionEnum.PapUnsupportedJwtException.getMsg());
        } else
        return response(code, this.buildMessage(request, error));
    }

    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }

    @Override
    protected HttpStatus getHttpStatus(Map<String, Object> errorAttributes) {
        int statusCode = (int) errorAttributes.get("code");
        if(HttpStatus.resolve(statusCode) != null) {
            return HttpStatus.valueOf(statusCode);
        } else {
            return HttpStatus.OK;
        }
    }

    /**
     * 构建异常信息
     * @param request
     * @param ex
     * @return
     */
    private String buildMessage(ServerRequest request, Throwable ex) {
        StringBuilder message = new StringBuilder("Failed to handle request [");
        message.append(request.methodName());
        message.append(" ");
        message.append(request.uri());
        message.append("]");
        if (ex != null) {
            message.append(": ");
            message.append(ex.getMessage());
        }
        return message.toString();
    }

    /**
     * 构建返回的JSON数据格式
     * @param status        状态码
     * @param errorMessage  异常信息
     * @return
     */
    public static Map<String, Object> response(int status, String errorMessage) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", status);
        map.put("message", errorMessage);
        map.put("data", null);
        return map;
    }
}